package com.green.common.surety.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import com.green.common.util.utils.Xml2MapUtils;

public class SendMessageUtil {
	private static final String _uc = "961665";// 帐号
	private static final String _zuc = "admin";// 子帐号
	private static final String _pwd = "MA6ZSB"; // 密码
	private static final String _host = "http://www.mxtong.net.cn:8080/GateWay/Services.asmx/DirectSend?";
	private static final String MARK = "【世华地产】";
	/**
	 * 发送短信
	 * 
	 * @param mobiles
	 *            String 接收号码 13612341234;15912341234;
	 * @param cont
	 *            String 短信内容
	 * @return String
	 * @throws Exception
	 */
	public static String sendSMS(String mobiles, String cont) throws Exception {
		return sendSMS(mobiles, cont, "");
	}

	/**
	 * 发送短信
	 * 
	 * @param mobiles
	 *            String 接收号码 13612341234;15912341234;
	 * @param cont
	 *            String 短信内容
	 * @param sendTime
	 *            String 发送时间，格式为 yyyy-mm-dd hh:mm:ss（为空则立即发送）
	 * @return String
	 * @throws Exception
	 */
	public static String sendSMS(String mobiles, String cont, String sendTime)
			throws Exception {
		cont = URLEncoder.encode(cont, "UTF-8"); // 短信内容需要编码
		StringBuffer buff = new StringBuffer(_host);
		buff.append("UserID=").append(_uc).append("&");
		buff.append("Account=").append(_zuc).append("&");
		buff.append("Password=").append(_pwd).append("&");
		buff.append("Phones=").append(mobiles).append("&");
		buff.append("Content=").append(cont+MARK).append("&");
		buff.append("SendTime=").append(sendTime).append("&");
		buff.append("SendType=").append(1).append("&");
		buff.append("PostFixNumber=").append("1");
		return submit(buff.toString());
	}

	/**
	 * GET提交
	 * 
	 * @param url
	 *            String
	 * @return String
	 * @throws Exception
	 */
	private static String submit(String url) throws Exception {
		String re = "";
		int byteMax = 50;
		URL myurl = new URL(url);
		URLConnection urlcon = myurl.openConnection();
		urlcon.setRequestProperty("Accept-Charset", "UTF-8");
		urlcon.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		urlcon.setUseCaches(false);
		urlcon.connect();
		InputStream inputstream = urlcon.getInputStream();
		byte[] buff = new byte[byteMax];
		ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
		int ins;
		while ((ins = inputstream.read(buff)) >= 0) {
			bytearrayoutputstream.write(buff, 0, ins);
		}
		re = new String(bytearrayoutputstream.toByteArray());
		re.trim();
		return re;
	}

	public static Map<String, String> analysisForXML(String res) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Document doc = Xml2MapUtils.xmlStr2XmlDocument(res);
			Element rootElement = doc.getRootElement();
			for (@SuppressWarnings("unchecked")
			Iterator<Element> iterator = rootElement.elementIterator(); iterator
					.hasNext();) {
				// 获取第一层子元素
				Element element = iterator.next();
				String name = element.getName();
				if ("RetCode".equals(name)) {
					map.put("RetCode", element.getText());
				} else if ("OKPhoneCounts".equals(name)) {
					// 发送成功手机号码数量
					map.put("OKPhoneCounts", element.getText());
				} else if ("StockReduced".equals(name)) {
					// 被扣减的短信量
					map.put("StockReduced", element.getText());
				} else if ("ErrPhones".equals(name)) {
					// 非法手机号码
					map.put("ErrPhones", element.getText());
				} else if ("Message".equals(name)) {
					// 操作失败原因
					map.put("Message", element.getText());
				}
			}
		} catch (Exception e) {
			return null;
		}
		return map;
	}

	public static void main(String[] args) {
		String s = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ROOT xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"JobSendedDescription\"><RetCode>Sucess</RetCode><JobID>108532088</JobID><OKPhoneCounts>1</OKPhoneCounts><StockReduced>1</StockReduced><ErrPhones>;</ErrPhones></ROOT>";
		System.out.println(analysisForXML(s));
	}

}
